/**
 * Created by Administrator on 2017/6/5.
 */

var React = require('react');

var IncreaseId = require('../../web/tools/IncreaseId');
var ajax = require('../tools/ajax');
var ShopPro = require('../components/ShopPro');
var Icon = require('../components/Icon');
var MsgBox = require('../components/MsgBox');

module.exports = React.createClass({
    getInitialState: function (){
        return {
            model:0,//0表示加入购物车模式，1表示生成订单模式
            list_info:[],
            ckGoods:[],
            flag:false,
            goods_price:0,//商品价格
            goods_stock:0,//库存
            goods_des:'',//选择的规格描述,
            goods_attr:[],
            goods_id:'',
            goods_number:1,
            attr_title:'',
            attr_name:'',
            goods_img:'',
            ckAttr:[],
            selectkCkAttr:null,
            word:"",//提示说明
            kucunFlag:false
        }
    },
    componentDidMount: function () {
        var p=this;
        if(p.props.model){
            p.setState({model:p.props.model});
        }
    },

    /**根据商品id获取商品详情*/
    getProinfoById:function(id){
        var p = this;
        ajax("POST","getProinfoById",{goods_id:id},function(dt){
            if(dt && dt.success){
                var objs = dt.data[0];
                console.log(objs);
                var kucunFlag = objs.goods_number > 0 ? true:false;
                p.setState({flag:true});
                if(objs.attr_value){
                    var attrList = objs.attr_value.split(',');
                    for(var i=0; i<attrList.length;i++){
                        p.state.ckAttr[attrList[i]] = attrList[i];
                    }
                    p.setState({
                        attr_title: objs.attr_name,
                        goods_attr: attrList
                    });
                }
                p.setState({
                    kucunFlag:kucunFlag,
                    list_info:objs,
                    goods_id: id,
                    goods_price: p.props.price,
                    goods_img:objs.goods_img
                });
            }
        });
    },
    /**判断购物车是否存在该商品，存在更新商品数量，否则增加到购物车*/
    addCart: function (){
        var p = this;
        var userId = localStorage.getItem('userId');
        var list_info = this.state.list_info;
        if(userId){
            var id = IncreaseId.increaseId();
            var goods_name = list_info.goods_name;
            var goods_id = p.state.goods_id;
            var goods_price = p.props.price;
            var goods_number = p.state.goods_number;
            var goods_attr = p.state.attr_name;
            var goods_type = list_info.goods_type;
            var good_tax_rate = list_info.good_tax_rate;
            var good_tax_fee = good_tax_rate / 100 * goods_price;
            var shop_id = localStorage.getItem("shopId");
            var judgeShop = localStorage.getItem("judgeShop");
            ajax("POST","getCartlistByGoodsId",{
                user_id:userId,
                goods_id:goods_id
            },function(dt){
                if(dt&&dt.success) {
                    var cartPro = dt.data;
                    console.log(cartPro);
                    if(cartPro.length>0){
                        if(cartPro[0].shop_id == judgeShop){
                            ajax("POST", "updateCart", {
                                user_id: userId,
                                goods_id: goods_id,
                                goods_number: goods_number,
                                good_tax_fee: good_tax_fee
                            }, function (dt) {
                                if (dt && dt.success) {
                                    p.setState({
                                        flag: false,
                                        word: '该商品购物车已存在'
                                    }, ()=> {
                                        p.props.MsgBox();
                                    });
                                }
                            });
                        }else {
                            if (!judgeShop) {
                                shop_id = "";
                            }
                            ajax("POST", "addCart", {
                                id: id,
                                user_id: userId,
                                goods_id: goods_id,
                                goods_name: goods_name,
                                goods_price: goods_price,
                                goods_number: goods_number,
                                goods_type: goods_type,
                                shop_id: shop_id,
                                goods_attr: goods_attr,
                                good_tax_fee: good_tax_fee
                            }, function (dt) {
                                if (dt && dt.success) {
                                    var cartNum = localStorage.getItem("cartNum");
                                    localStorage.cartNum = parseInt(cartNum) + 1;
                                    p.setState({
                                        flag: false,
                                        word: '添加购物车成功'
                                    }, ()=> {
                                        p.props.MsgBox();
                                    });
                                    if (p.props.fleshNum) {
                                        p.props.fleshNum();
                                    }
                                }
                            });
                        }
                    } else {
                        if(!judgeShop){
                            shop_id = "";
                        }
                        ajax("POST","addCart",{
                            id:id,
                            user_id:userId,
                            goods_id:goods_id,
                            goods_name:goods_name,
                            goods_price:goods_price,
                            goods_number:goods_number,
                            goods_type:goods_type,
                            shop_id:shop_id,
                            goods_attr:goods_attr,
                            good_tax_fee:good_tax_fee
                        },function(dt){
                            if(dt && dt.success){
                                var cartNum =localStorage.getItem("cartNum");
                                localStorage.cartNum = parseInt(cartNum)+1;
                                p.setState({
                                    flag: false,
                                    word:'添加购物车成功'
                                },()=>{
                                    p.props.MsgBox();
                                });
                                if(p.props.fleshNum){
                                    p.props.fleshNum();
                                }
                            }
                        });
                    }
                }
            });
        } else{
            location.href = '#login';
        }
    },

    /**积分兑换,直接生成订单*/
    order(){
        var p = this;
        var order_id = IncreaseId.increaseId();
        var list_info = p.state.list_info;
        var userId = localStorage.getItem('userId');
        console.log(p.props.jifen);
        console.log(list_info.point*p.state.goods_number);
        if(p.props.jifen >= list_info.point*p.state.goods_number) {
            ajax("POST", "addOrderGoods", {
                order_id: order_id,
                goods_id: list_info.id,
                shop_id: "",
                goods_name: list_info.goods_name,
                goods_price: list_info.point_price,
                goods_number: p.state.goods_number,
                goods_type: list_info.goods_type,
                goods_attr: list_info.goods_attr,
                good_tax_fee: list_info.good_tax_fee,
                is_discount: 0
            }, function (dt) {
                if (dt && dt.success) {
                    console.log("添加成功");
                }
            });
            var order_sn = p.orderSn();
            var add_time = new Date().getTime();
            ajax("POST", "addOrderInfo", {
                orderId: order_id,
                order_sn: order_sn,
                user_id: userId,
                order_status: 0,
                shipping_status: 0,
                pay_status: 0,
                goods_amount: list_info.point_price * p.state.goods_number,
                shipping_fee: 0,
                order_amount: list_info.point_price * p.state.goods_number,
                goods_tax: 0,
                add_time: add_time,
                order_point: list_info.point * p.state.goods_number
            }, function (dt) {
                if (dt && dt.success) {
                    localStorage.setItem("orderId", order_id);
                    location.href = '#orderInfo';
                }
            });
        }else{
            p.props.MsgBox();
        }
    },
    /**生成order_sn*/
    orderSn(){
        var now = new Date();
        var year = now.getFullYear();       //年
        var month = now.getMonth() + 1;     //月
        var day = now.getDate();            //日
        var clock = year;
        if(month < 10) {
            clock = clock+ "0" + month;
        }else{
            clock +=month;
        }
        if(day < 10) {
            clock = clock+ "0" + day;
        }else{
            clock +=day;
        }
        var random ='';
        for(var i=0;i<6;i++){
            random += Math.floor(Math.random()*10);
        }
        clock += random;
        return(clock);
    },
    /**增加商品数量*/
    increase:function(){
        var number = this.refs.number.innerText;
        var num = this.state.list_info.goods_number;//库存
        if(number < num){
            number = parseInt(number) + 1;
        }
        this.setState({goods_number:number});
    },
    /**减去商品数量*/
    reduce:function(){
        var number = this.refs.number.innerText;
        var num = 1;
        if (number != 1){
            num = parseInt(number) - 1;
        }
        this.setState({goods_number:num});
    },
    /**关闭弹出层*/
    close:function(){
        var flag = this.state.flag;
        if(flag){
            this.setState({flag:false})
        }
    },
    /**选择属性*/
    ckAttr:function(e){
        var attr = e.currentTarget.getAttribute('data-attr');
        this.setState({selectkCkAttr:attr});
        this.setState({attr_name:attr});
    },
    kucun(){
        this.setState({word:"库存不足"},()=>{
            this.props.MsgBox();
        });
    },
    render: function () {
        var p=this;
        var price = localStorage.getItem("price");
        var index = 0;
        var list_info = this.state.list_info;
        if(p.state.goods_attr) {
            var attrlist = p.state.goods_attr.map(function (obj) {
                index++;
                return (
                    <label key={index} onClick={p.ckAttr} data-attr={obj} style={{color:p.state.selectkCkAttr == obj ? "red" : "gray"}}>
                        {obj}
                    </label>
                )
            });
        }
        if(list_info.goods_img){
           var imgUrl = list_info.goods_img.split(",")[0];
        }
        return (
            <div className="attr-content" style={{display:p.state.flag?"block":"none"}}>
                <div className="mui-cover show" id="s-decision-wrapper">
                    <div className="summary">
                        <div className="img"> <img src={imgUrl}/> </div>
                        <div className="main-r">
                            <div className="priceContainer">
                                {p.state.model?"¥"+list_info.point_price+"+"+list_info.point+"积分":"¥"+price}
                            </div>
                            <div className="stock-control"><span className="stock">库存{list_info.goods_number}件</span><span className="limitTip"></span></div>
                        </div>
                        <div className="sback" aria-label="关闭" onClick={p.close}>
                            <Icon icon="#icon-shanchu" style={{width:".8rem",height:".8rem"}}/>
                        </div>
                    </div>
                    <div className="body">
                        <section className="s-decision">
                            <div className="address-control"></div>
                            <div className="sku-control">
                                <ul className="mui-sku">
                                    <li key={index} className="J_SkuGroup mui-sku-group ">
                                        <h2>{list_info.attr_name}</h2>
                                        <div className="items"  role="radiogroup">
                                            {attrlist}
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div className="number">
                                <h2>购买数量</h2>
                                <div className="content">
                                    <span className="num" onClick={p.reduce} data-number={p.state.goods_number}>-</span>
                                    <span ref="number">{p.state.goods_number}</span>
                                    <span className="num" onClick={p.increase} data-number={p.state.goods_number}>+</span>
                                </div>
                            </div>
                        </section>
                    </div>
                    <div className="option mui-flex">
                        <button className="ok cell" onClick={p.state.kucunFlag?(p.state.model?p.order:p.addCart):p.kucun}>{p.state.model?"去兑换":"确定"}</button>
                    </div>
                </div>
            </div>
        )
    }
});
